﻿using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Core.Common;
using Core.Common.Monitor;
using Core.Expansion;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using Tool;
using Tool.Common;
using Tool.Expansion;
using Tool.Web.HttpHelper;
using Tool.Windows.Win32;
using static Core.Common.Global;
using Tweet = Core.Common.Tweeter.Tweet;

namespace Core.Monitors
{
	public class TweeterMonitor : Tool.Common.Monitor
	{
		private readonly Hashtable hashtable = new Hashtable();
		private readonly Tweeter tweeter;
		private readonly string userId;

		public TweeterMonitor(object flag) : base(flag)
		{
			ClearAllCloseEvent();
			ClearAllStartEvent();
			CloseEvent += () => CQ.Log($"关闭了对{flag}的推文监控任务");
			StartEvent += () => CQ.Log($"开启了对{flag}的推文监控任务");
			WebClient webClient = new WebClient { Proxy = Proxy };
			if (!string.IsNullOrWhiteSpace(TweetConfig.Authorization))
				tweeter = new Tweeter(ref webClient, TweetConfig.Authorization, TweetConfig.Path, TweetConfig.Token);
			else
			{
				tweeter = new Tweeter(ref webClient);
				TweetConfig.Authorization = tweeter.Authorization;
				TweetConfig.Path = tweeter.Path;
				TweetConfig.Token = tweeter.Token;
			}
			userId = tweeter.GetUserID(flag.ToString());
		}

		protected override void Handle()
		{
			var list = tweeter.GetTweets(userId);
			if (list.Length == 0)
			{
				CQ.Log("本次" + flag + "推文无数据");
				return;
			}
			if (hashtable.Count == 0)
			{
				foreach (Tweet item in list)
				{
					if (hashtable.Contains(item.ID))
					{
						hashtable[item.ID] = true;
					}
					else
					{
						hashtable.Add(item.ID, true);
					}
				}
				return;
			}
			//var translate = Win32Help.IniReadValue(AppDir + "高级设置.ini", "推文监控", "自动翻译", "关") == "开" ? true : false;
			var translate = false;
			var 拒绝转推 = Win32Help.IniReadValue(AppDir + "高级设置.ini", "推文监控", "拒绝转推", "关") == "开" ? true : false;
			for (int i = 0; i < list.Length; i++)
			{
				Tweet tweet = list[i];
				if (拒绝转推 && tweet.IsOnlyRetweet) continue;
				if (!hashtable.Contains(tweet.ID))
				{
					MonitorInfo monitorInfo = TweetInfo.Find(e => e.flag == (string)flag);
					if (translate) tweet.Content = Translate(tweet.Content);
					lock (monitorInfo)
					{
						string text = "您监控的推主" + flag + (tweet.IsOnlyRetweet ? "转" : "发") + "推了\n" + GetContent(tweet);
						foreach (MonitorItem item2 in monitorInfo.item)
						{
							if (item2.status == 1)
							{
								if (item2.type == 0)
								{
									CQ.SendGroupMessage(item2.num, text);
								}
								if (item2.type == 1)
								{
									CQ.SendPrivateMessage(item2.num, text);
								}
							}
							Thread.Sleep(1000);
						}
					}
					hashtable.Add(tweet.ID, true);
				}
			}
		}

		string GetContent(Tweet tweet)
		{
			string temp = tweet.Content;
			string img = string.Empty;
			if (tweet.Media != null)
			{
				foreach (var item in tweet.Media)
				{
					if (item["type"].ToString() == "photo")
					{
						string text2 = ImagePath + TimeHelp.GetCurrentTimeUnix(IsMilliseconds: true).ToString() + ".jpg";
						File.WriteAllBytes(text2, HttpNet.Get(item["media_url_https"].ToString(), null, null, null, 10000, Proxy));
						img += CQ.Code_Image(text2.HandleImagePath());
					}
				}
			}
			if (tweet.IsOnlyRetweet)
			{
				if (tweet.Retweet == null)
				{
					return string.Empty;
				}
				else
				{
					return tweet.Retweet.UserName + "：" + GetContent(tweet.Retweet);
				}
			}
			else
			{
				var time = "\n发送时间：" + tweet.CreatTime.ToString("yyyy-MM-dd HH:mm");
				if (tweet.Retweet == null) return temp + img + time;
				else return temp + img + time + "\n" + tweet.Retweet.UserName + "：\n" + GetContent(tweet.Retweet);
			}
		}


		private string Translate(string text)
		{
			StringBuilder sb = new StringBuilder(text);
			sb.Append("\n\n翻译结果：");
			string[] array = text.Split('\n');
			for (int i = 0; i < array.Length; i++)
			{
				if (i <= 1) continue;
				sb.Append("\n" + array[i].Translate());
			}
			return sb.ToString();
		}
	}
}
